/*
钓鱼游戏主管理器
整合水面、钓鱼竿、鱼类系统
专为VR钓鱼游戏设计
*/

import * as THREE from 'three';
import { WaterSurface } from '../environment/WaterSurface.js';
import { FishingRod } from './FishingRod.js';
import { FishManager } from './FishManager.js';
import { renderer } from '../core/init.js';

class FishingManager {
  constructor(scene, camera, ui) {
    this.scene = scene;
    this.camera = camera;
    this.ui = ui;
    
    // 游戏系统
    this.waterSurface = null;
    this.fishingRod = null;
    this.fishManager = null;
    
    // 游戏状态
    this.gameState = 'idle'; // idle, fishing, fighting, caught
    this.currentFish = null;
    this.fishingTime = 0;
    this.biteChance = 0;
    
    // 鼠标/触摸控制（非VR模式）
    this.raycaster = new THREE.Raycaster();
    this.mouse = new THREE.Vector2();
    
    // 统计数据
    this.stats = {
      totalCaught: 0,
      totalTime: 0,
      bestFish: null,
      experience: 0
    };
    
    this.init();
  }
  
  init() {
    this.createWaterSurface();
    this.createFishingRod();
    this.createFishManager();
    this.setupEventListeners();
    this.setupNonVRControls();
  }
  
  createWaterSurface() {
    // 创建水面系统
    this.waterSurface = new WaterSurface(this.scene, {
      size: 50,
      segments: 100,
      color: 0x006994,
      transparency: 0.8,
      waveSpeed: 0.3,
      waveHeight: 0.2
    });
    
    console.log('🌊 水面系统已创建');
  }
  
  createFishingRod() {
    // 创建钓鱼竿系统
    this.fishingRod = new FishingRod(this.scene, renderer);
    
    console.log('🎣 钓鱼竿系统已创建');
  }
  
  createFishManager() {
    // 创建鱼类管理系统
    this.fishManager = new FishManager(this.scene);
    
    console.log('🐟 鱼类管理系统已创建');
  }
  
  setupEventListeners() {
    // 监听钓鱼竿事件
    document.addEventListener('bobberLanding', (event) => {
      const { position, intensity } = event.detail;
      this.waterSurface.createRipple(position.x, position.z, intensity);
      this.startFishing(position);
    });
    
    document.addEventListener('fishBite', (event) => {
      const { position, intensity } = event.detail;
      this.waterSurface.createFishBite(position.x, position.z, intensity);
    });
  }
  
  setupNonVRControls() {
    // 非VR模式的鼠标控制
    window.addEventListener('click', (event) => {
      if (!renderer.xr.isPresenting) {
        this.handleNonVRClick(event);
      }
    });
    
    window.addEventListener('mousemove', (event) => {
      this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    });
  }
  
  handleNonVRClick(event) {
    // 更新鼠标位置
    this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    
    // 射线检测
    this.raycaster.setFromCamera(this.mouse, this.camera);
    
    // 检测水面点击
    const waterHit = this.waterSurface.detectFishingClick(this.raycaster);
    
    if (waterHit.hit) {
      console.log('🎣 非VR模式钓鱼点击:', waterHit.position);
      
      // 模拟抛竿
      this.simulateNonVRCasting(waterHit.position);
    }
  }
  
  simulateNonVRCasting(targetPosition) {
    // 非VR模式下模拟抛竿
    this.fishingRod.bobberPosition.copy(targetPosition);
    this.fishingRod.bobberPosition.y = this.waterSurface.getWaterHeight(targetPosition.x, targetPosition.z);
    this.fishingRod.bobber.position.copy(this.fishingRod.bobberPosition);
    
    // 开始钓鱼
    this.startFishing(targetPosition);
  }
  
  startFishing(position) {
    if (this.gameState !== 'idle') return;
    
    console.log('🎣 开始钓鱼:', position);
    
    this.gameState = 'fishing';
    this.fishingTime = 0;
    this.biteChance = 0;
    
    // 更新UI
    this.ui.showFishingStatus('等待鱼咬钩...');
    
    // 在附近生成一些鱼
    this.fishManager.spawnFishNearPosition(position, 3);
  }
  
  updateFishingLogic(deltaTime) {
    if (this.gameState !== 'fishing') return;
    
    this.fishingTime += deltaTime;
    
    // 随时间增加咬钩概率
    this.biteChance = Math.min(this.fishingTime * 0.1, 0.8);
    
    // 随机检测鱼咬钩
    if (Math.random() < this.biteChance * deltaTime) {
      this.triggerFishBite();
    }
    
    // 更新UI显示等待时间
    this.ui.updateFishingTime(this.fishingTime);
  }
  
  triggerFishBite() {
    console.log('🐟 鱼咬钩了！');
    
    this.gameState = 'fighting';
    
    // 获取一条随机鱼
    this.currentFish = this.fishManager.getRandomFish();
    
    // 触发钓鱼竿的鱼咬钩动画
    this.fishingRod.simulateFishBite(this.currentFish.struggle);
    
    // 更新UI
    this.ui.showFishingStatus(`${this.currentFish.name}咬钩了！快收竿！`);
    this.ui.showFishBattleUI(this.currentFish);
    
    // 开始鱼的战斗逻辑
    this.startFishBattle();
  }
  
  startFishBattle() {
    const battleDuration = this.currentFish.struggle * 1000; // 战斗时长
    let battleProgress = 0;
    
    const battleLoop = () => {
      battleProgress += 16; // 假设60FPS
      
      // 更新战斗进度
      const progress = Math.min(battleProgress / battleDuration, 1);
      this.ui.updateBattleProgress(progress);
      
      // 随机触发挣扎效果
      if (Math.random() < 0.1) {
        this.fishingRod.simulateFishBite(this.currentFish.struggle * 0.5);
        this.waterSurface.createRipple(
          this.fishingRod.bobberPosition.x,
          this.fishingRod.bobberPosition.z,
          this.currentFish.struggle
        );
      }
      
      if (progress < 1) {
        requestAnimationFrame(battleLoop);
      } else {
        this.completeFishCatch();
      }
    };
    
    battleLoop();
  }
  
  completeFishCatch() {
    console.log('🎉 成功钓到鱼！', this.currentFish);
    
    this.gameState = 'caught';
    
    // 更新统计
    this.stats.totalCaught++;
    this.stats.experience += this.currentFish.experience;
    
    if (!this.stats.bestFish || this.currentFish.weight > this.stats.bestFish.weight) {
      this.stats.bestFish = this.currentFish;
    }
    
    // 显示钓鱼结果
    this.ui.showFishCatchResult(this.currentFish, this.stats);
    
    // 创建鱼的3D模型并显示
    this.fishManager.createCaughtFishModel(this.currentFish, this.fishingRod.bobberPosition);
    
    // 3秒后重置状态
    setTimeout(() => {
      this.resetFishingState();
    }, 3000);
  }
  
  resetFishingState() {
    console.log('🔄 重置钓鱼状态');
    
    this.gameState = 'idle';
    this.currentFish = null;
    this.fishingTime = 0;
    this.biteChance = 0;
    
    // 重置UI
    this.ui.hideFishBattleUI();
    this.ui.showFishingStatus('准备钓鱼');
  }
  
  // 环境系统
  updateEnvironment(deltaTime, waterTime) {
    // 根据时间改变环境
    const timeOfDay = (waterTime % 120) / 120; // 2分钟一个昼夜循环
    
    if (timeOfDay < 0.25) {
      // 清晨 (蓝色调)
      this.scene.background.setHex(0x87CEEB);
      this.waterSurface.setWaterColor(0x4682B4);
    } else if (timeOfDay < 0.5) {
      // 白天 (明亮)
      this.scene.background.setHex(0x87CEEB);
      this.waterSurface.setWaterColor(0x006994);
    } else if (timeOfDay < 0.75) {
      // 傍晚 (橙色调)
      this.scene.background.setHex(0xFFA500);
      this.waterSurface.setWaterColor(0xFF8C00);
    } else {
      // 夜晚 (深蓝色)
      this.scene.background.setHex(0x191970);
      this.waterSurface.setWaterColor(0x000080);
    }
  }
  
  // 主更新方法
  update(deltaTime) {
    const waterTime = performance.now() * 0.001;
    
    // 更新各个系统
    if (this.waterSurface) {
      this.waterSurface.update(deltaTime, waterTime);
    }
    
    if (this.fishingRod) {
      this.fishingRod.update(deltaTime);
    }
    
    if (this.fishManager) {
      this.fishManager.update(deltaTime);
    }
    
    // 更新钓鱼逻辑
    this.updateFishingLogic(deltaTime);
    
    // 更新环境
    this.updateEnvironment(deltaTime, waterTime);
    
    // 更新统计
    this.stats.totalTime += deltaTime;
    
    // 更新UI
    this.ui.updateStats(this.stats);
  }
  
  // 销毁资源
  destroy() {
    if (this.waterSurface) {
      this.waterSurface.destroy();
    }
    
    if (this.fishingRod) {
      this.fishingRod.destroy();
    }
    
    if (this.fishManager) {
      this.fishManager.destroy();
    }
    
    // 移除事件监听器
    document.removeEventListener('bobberLanding', this.handleBobberLanding);
    document.removeEventListener('fishBite', this.handleFishBite);
  }
}

export { FishingManager }; 